<?php
namespace alisms;

use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use Aliyun\Core\Config;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Core\Profile\DefaultProfile;

class Alisms
{

    static $acsClient = null;

    /**
     * 取得AcsClient
     *
     * @return DefaultAcsClient
     */
    public static function client($accessKeyId, $accessKeySecret)
    {
        if (static::$acsClient === null) {
            $profile = DefaultProfile::getProfile('cn-hangzhou', $accessKeyId, $accessKeySecret);
            DefaultProfile::addEndpoint('cn-hangzhou', 'cn-hangzhou', 'Dysmsapi', 'dysmsapi.aliyuncs.com');
            static::$acsClient = new DefaultAcsClient($profile);
        }
        return static::$acsClient;
    }

    /**
     * 发送短信
     * @return stdClass
     */
    public static function send($accessKeyId, $accessKeySecret, $PhoneNumbers, $SignName, $TemplateCode, $TemplateParam = [])
    {
        Config::load();
        header('Content-Type: text/plain; charset=utf-8');
        $request = new SendSmsRequest();
        $request->setPhoneNumbers($PhoneNumbers);
        $request->setSignName($SignName);
        $request->setTemplateCode($TemplateCode);
        if (!empty($TemplateParam)) {
            $request->setTemplateParam(json_encode($TemplateParam, JSON_UNESCAPED_UNICODE));
        }
        try {
            $response = static::client($accessKeyId, $accessKeySecret)->getAcsResponse($request);
            if ($response->Code == 'OK') {
                return true;
            }
            trace('阿里大鱼短信发送失败:' . $response->Message);
            return false;
        } catch (\Exception $e) {
            trace('阿里大鱼短信发送异常:' . $e->getMessage());
            return false;
        }
    }
}
